//
//  main.cpp
//  ThreadGetResourceStudy
//
//  Created by huge on 2021/8/2.
//  Copyright © 2021 huge. All rights reserved.
//

#include <iostream>
#include <thread>

std::mutex mutex;
std::condition_variable cond;
int count = 10;

void thread1(int val){
    
    while (true) {
        std::unique_lock<std::mutex> ulock(mutex);
//        std::lock_guard<std::mutex>lockg(mutex);
//        mutex.lock();
        count++;
        std::cout << "thread1: " << val << "  pid: "
        << std::this_thread::get_id() << " count:" <<count << "\n";
        
        struct timeval time;
        printf("thread1 s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));
        ulock.unlock();
        cond.notify_one();
        
        std::this_thread::sleep_for(std::chrono::milliseconds(1));

//        mutex.unlock();
    }
    
}

void thread2(int val){
    while (true) {
//        mutex.lock();
//        std::lock_guard<std::mutex>lockg(mutex);
        std::unique_lock<std::mutex>locker(mutex);
        count--;
        std::cout << "thread2: " << val << "  pid: "
        << std::this_thread::get_id() << " count:" <<count << "\n";

        cond.wait(locker);
        struct timeval time;
        printf("thread2 s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));
        locker.unlock();
//        mutex.unlock();
//    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}




int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    
    std::thread first(thread1,1);
    std::thread second(thread2,2);

    first.join();
    second.join();

    return 0;
}
